package com.xm.linxiaogang.base.activity.swipeback

import android.app.Activity
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import java.util.*

/**
 * 监听所有Activity的生命周期，并管理Activity
 */
class ActivityLifecycleHelper : ActivityLifecycleCallbacks {

    companion object {

        //单例
        private var singleton: ActivityLifecycleHelper? = null

        //对象锁
        private val lockObj = Any()

        //装载Activity的堆栈
        private var activities = LinkedList<Activity>()

        fun build(): ActivityLifecycleHelper? {
            synchronized(lockObj) {
                if (singleton == null) {
                    singleton = ActivityLifecycleHelper()
                }
                return singleton
            }
        }

        //获取最后一个的Activity
        fun getLatestActivity(): Activity? {
            val count = activities.size
            if (count == 0) {
                return null
            }
            return activities[count - 1]
        }

        //获取上一个Activity
        fun getPreviousActivity(): Activity? {
            val count = activities.size
            if (count < 2) {
                return null
            }
            return activities[count - 2]
        }
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        addActivity(activity)
    }

    override fun onActivityStarted(activity: Activity) {

    }

    override fun onActivityResumed(activity: Activity) {

    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {

    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
        remove(activity)
    }

    //添加Activity到堆栈
    private fun addActivity(activity: Activity) {
        activities.add(activity)
    }

    //从堆栈中移除Activity
    private fun remove(activity: Activity) {
        if (activities.contains(activity)) {
            activities.remove(activity)
        }
    }

}